<template>
  <div class="wrap">
    <p class="font20 color333 mb30">事件判断</p>
    <!-- 事件选择 -->
    <el-form :inline="true" :model="ruleForm" size="mini" ref="ruleForm"  :rules="ruleFormRules" class="mb60">
      <!-- 事件类型 -->
      <el-form-item label="事件类型：" prop="eventType" required class="noMargin mr30 noMarginBottom ">
        <el-select v-model="ruleForm.eventType" placeholder="选择事件类型" size="mini" @change="changeType" clearable class="w225" >
          <el-option
            v-for="item in eventList"
            :key="item.id"
            :label="item.tagName"
            :value="item.type"
          ></el-option>
        </el-select>
      </el-form-item>

      <!-- 具体事件 -->
      <el-form-item label="事件：" prop="eventCode" required class="noMarginBottom ">
        <el-select v-model="ruleForm.eventCode" placeholder="选择事件" size="mini" @change="changeCode" clearable class="w225" >
          <el-option
            v-for="item in eventCodeList"
            :key="item.id"
            :label="item.tagName"
            :value="item.id"
          ></el-option>
        </el-select>
      </el-form-item>

      <!-- 消费事件---优惠券核销部分 -->
      <div class="form-wrap"  v-if="ruleForm.eventType == 2 && ruleForm.eventCode == 'coupons_verification'">
        <div class="label mt30">
          <span style="color:red">*</span>
          <span class="color333 font16">事件条件：</span>
        </div>
        <div class="form mt30" v-for="(item,index) in formDataList" :key="index">
          <el-form :model="item" size="mini" ref="itemFrom" class="mb10 commonForm"  :rules="eventNodeRules">
            <i v-if="index != 0" class="el-icon-close delete f_r mb30" @click=deleteForm(item) ></i>
              <el-form-item :label="'事件条件' + (index + 1) + '：'" prop="eventName" class="labelColor666 labelSize14 mb20 labelMarginLeft5" required>
                <el-input v-model="item.eventName" placeholder='请输入名称' size="mini" clearable maxlength="10" class="mr10 w244"></el-input>
                <span class="desc">提示:请输入1-10个字符</span>
              </el-form-item>
              <el-form-item label="时间条件：" prop="eventRangeTime" class="labelColor666 labelSize14 labelMarginLeft14 mb20">
                <el-date-picker
                  v-model="item.eventRangeTime"
                  type="datetimerange"
                  range-separator="至"
                  start-placeholder="开始时间"
                  end-placeholder="结束时间"
                  value-format="timestamp"
                  :picker-options="timeCheck"
                  class="w385"
                >
                </el-date-picker>
              </el-form-item>
              <el-form-item >
              <span class="desc">说明：系统执行该动作后，判断到限制结束时间时没有发生动作相关事件（例：到限制结束时间时，用户没有去核销优惠券）。</span>
              </el-form-item>
              <el-form-item label="优惠券活动：" prop="promCode" class="labelColor666 labelSize14 mb20 ">
                <el-select v-model="item.promCode" filterable placeholder="请选择优惠券活动" size="mini"  class="w385" remote :remote-method="getCouponsList" :loading="loadPromsing"  @focus="getCurrentNodeForm(index)" clearable @clear="getCouponList()">
                  <el-option
                    v-for="itm in activeStatus"
                    :key="itm.promotionId"
                    :label="itm.promName"
                    :value="itm.promotionId"
                  ></el-option>
                </el-select>
              </el-form-item>
              <el-form-item label="核销渠道：" prop="verificationChannels"  class="labelColor666 labelSize14 labelMarginLeft25 noMarginBottom mt10">
                <el-select v-model="item.verificationChannels" filterable clearable placeholder="请选择" size="mini"  class="w385">
                  <el-option
                    v-for="itm in channelStatus"
                    :key="itm.id"
                    :label="itm.tagName"
                    :value="itm.id"
                  ></el-option>
                </el-select>
              </el-form-item>
          </el-form>
          <!-- 新增按钮 -->
          <el-button type="primary" v-if="formDataList.length <= 0" @click="addForm">新增分支</el-button>
        </div>
      </div>


      <!-- 消费事件---红包核销部分 -->
      <div class="form-wrap"  v-if="ruleForm.eventType == 2 && ruleForm.eventCode == 'redEnvelope_verification'">
        <div class="label mt30">
          <span style="color:red">*</span>
          <span class="color333 font16">事件条件：</span>
        </div>
        <div class="form mt30" v-for="(item,index) in formDataList" :key="index">
          <el-form :model="item" size="mini" ref="itemFrom" class="mb10 commonForm"  :rules="eventNodeRules">
            <i v-if="index != 0" class="el-icon-close delete f_r mb30" @click=deleteForm(item)></i>
              <el-form-item :label="'事件条件' + (index + 1) + '：'" prop="eventName" class="labelColor666 labelSize14 mb20" required>
                <el-input v-model="item.eventName" placeholder='请输入名称' size="mini" clearable maxlength="10" class="w244 mr10"></el-input>
                <span class="desc">提示:请输入1-10个字符</span>
              </el-form-item>
              <el-form-item label="时间条件：" prop="eventRangeTime" class="labelColor666 labelSize14 labelMarginLeft8 mb20" required>
                <el-date-picker
                  v-model="item.eventRangeTime"
                  type="datetimerange"
                  range-separator="至"
                  start-placeholder="开始时间"
                  end-placeholder="结束时间"
                  value-format="timestamp"
                  :picker-options="timeCheck"
                  class="w390"
                >
                </el-date-picker>
              </el-form-item>
              <el-form-item>
                <span class="desc">说明：系统执行该动作后，判断到限制结束时间时没有发生动作相关事件（例：到限制结束时间时，用户没有去核销红包）。</span>
              </el-form-item>
              <el-form-item label="红包活动：" prop="promCode" class="labelColor666 labelSize14 labelMarginLeft8 mb20" required>
                <el-select v-model="item.promCode" class="w390"  filterable placeholder="请选择红包活动" size="mini" remote :remote-method="getCouponsList" :loading="loadPromsing" @focus="getCurrentNodeForm(index)" clearable @clear="getCouponList()">
                  <el-option
                    v-for="itm in activeStatus"
                    :key="itm.promotionId"
                    :label="itm.promName"
                    :value="itm.promotionId"
                  ></el-option>
                </el-select>
              </el-form-item>
              <el-form-item label="核销渠道：" prop="verificationChannels" class="labelColor666 labelSize14 labelMarginLeft16 noMarginBottom mt10">
                <el-select v-model="item.verificationChannels" class="w390 " filterable placeholder="请选择" size="mini" clearable >
                  <el-option
                    v-for="itm in channelStatus"
                    :key="itm.id"
                    :label="itm.tagName" 
                    :value="itm.id"
                  ></el-option>
                </el-select>
              </el-form-item>
          </el-form>
          <!-- 新增按钮 -->
          <el-button type="primary" v-if="formDataList.length <= 0" @click="addForm">新增分支</el-button>
        </div>
      </div>


    </el-form>

    <!-- 取消 确定按钮 -->
    <div class="t_c">
      <el-button class="cancelButton mr60" @click="handleClose()">取消</el-button>
      <el-button class="searchButton" @click="saveNodeBranchConfig()" type="primary">确定</el-button>
    </div>

  </div>
</template>

<script>
  import {eventList, levelList, activeStatus, channelStatus, pointsExchangeContents, getEventCodeListByType, checkRemoveJsonProperties } from './event/crmEventJudge'
  // 自动化营销-----事件选择组件
  export default {
    name: 'eventJudge',
    components: {

    },

    props: {
      journeyId: {
        type: String,
        default: '',
      },
      id: Number,
      nodeInfo: {
        type: Object,
      }
    },

    data() {
      //选择优惠券红包时需要判断活动时间是否重合
      var checkPromCode = (rule, value, callback) => {
        if (!value) {
          let msg = "请设置活动";
          if(this.ruleForm.eventCode == 'coupons_verification'){
            msg = "请设置优惠券活动";
          }else if(this.ruleForm.eventCode == 'redEnvelope_verification'){
            msg = "请设置红包活动";
          }
          return callback(new Error(msg));
        } else {
          let promCode = this.currentNodeForm.promCode;
          //判断时间是否有重叠
          let currentProm = this.activeStatus.find(function (item, index) {
            return item.promotionId == promCode;
          })
          if(this.currentNodeForm.eventRangeTime){
            let timeMsgPre = this.ruleForm.eventCode == 'coupons_verification' ? '优惠券' : '红包';
            let timeMsg = timeMsgPre + '有效时间与时间条件有冲突，无法正常触发，请修改时间条件或重新选择' + timeMsgPre;
            let start = new Date(this.currentNodeForm.eventRangeTime[0]).getTime();
            let end = new Date(this.currentNodeForm.eventRangeTime[1]).getTime();
            let promStart = new Date(currentProm["couponUseStartTime"]).getTime();
            let promEnd = new Date(currentProm["couponUseEndTime"]).getTime();
            if(end < promStart || start > promEnd){
              return callback(new Error(timeMsg));
            }
          }
          return callback();
        }
      };

      return {
        //旅程开始结束时间
        tripStart: null,
        tripEnd: '2037-06-26 10:10:20',
        //保存当前校验表单值
        currentNodeForm: {},
        currentNodeIndex: null,
        loadPromsing: false,
        // 表单数据
        ruleForm: {
          eventType: null,
          eventCode: null,
        },
        ruleFormRules:{
          eventType: [
            { required: true, message: "请设置事件类型", trigger: "change"},
          ],
          eventCode: { required: true, message: "请设置事件", trigger: "change" },
        },
        // 表单验证数据
        eventNodeRules:{
          //公共参数校验
          eventName: [
            { required: true, message: "请设置事件名称" },
            { min: 1, max: 10, message: "长度在 1 到 10 个字符", trigger: "blur" }
          ],
          eventRangeTime: [
            { required: true, message: "请设置时间条件", trigger: "blur"},
          ],
          //优惠券红包核销事件-优惠券红包code
          promCode: [{ required: true, validator: checkPromCode, trigger: "change" }],

        },
        eventList: eventList,
        eventCodeList:　[],               // 具体事件下拉数据，根据选择的事件类型来确定
        // 升级级数数据
        levelList: levelList,
        // 升降级所有表单数据
        formDataList: this.getDefalutItemFrom(),
        // 活动时间校验-如果是固定时间
        timeCheck: {
          disabledDate: time => {
            if(this.tripInfo.timeType == 1){
              //开始时间是当天
              if(new Date().toDateString().slice(0, 10) === new Date(this.tripStart).toDateString().slice(0, 10)){
                return time.getTime() > new Date(this.tripEnd).getTime() || time.getTime() <
                  new Date(this.tripStart).getTime() - 8.64e7;
              }
              return time.getTime() > new Date(this.tripEnd).getTime() || time.getTime() <
                new Date(this.tripStart).getTime()
            }
            return time.getTime() < Date.now() - 8.64e7;
          }
        },
        // 优惠券（红包）活动状态下拉框数据
        activeStatus: [],
        // 核销渠道数据
        channelStatus: channelStatus,
        //积分兑换内容
        pointsExchangeContents: pointsExchangeContents,
        tripInfo: {},
      }
    },

    methods: {
      //获取当前表单数据
      getCurrentNodeForm(index){
        this.currentNodeForm = this.formDataList[index];
        this.currentNodeIndex = index;
        this.getCouponList();
      },

      // 事件类型切换（对应的事件要跟着切换）
      changeType() {
        let eventType = this.ruleForm.eventType;
        this.eventCodeList = getEventCodeListByType(this.ruleForm.eventType);
        this.$refs["ruleForm"].resetFields();
        this.ruleForm.eventType = eventType;
      },

      // 事件切换
      changeCode(){
        this.formDataList = this.getDefalutItemFrom();
        this.getCouponList();
        if(this.$refs["itemFrom"]){
          if(this.$refs["itemFrom"][0]){
            this.$refs["itemFrom"][0].clearValidate();
          }
        }
      },

      // 会员升级-------添加事件
      addForm() {
        let list = this.formDataList;
        list.push(this.getDefalutItemFrom()[0]);
        this.formDataList = list;
      },

      // 会员升级----------删除事件
      deleteForm(data) {
        this.$confirm("确认要删除该模块吗?", "提示", {
          type: "warning"
        }).then(() => {
          const list = this.formDataList;
          list.forEach((item,index) => {
            if(data.id == item.id) {
              list.splice(index, 1)
            }
          });
          list.forEach((item,index) => {
            item.label = index > 0 ? '事件条件'+ index : '事件条件'
          })
        }).catch(() => {});

      },

      // 保存设置条件
      saveNodeBranchConfig(){
        let this_ = this;
        this.$refs["ruleForm"].validate(valid => {
          if (valid) {
            let checkFlag = true;
            this.$refs["itemFrom"].forEach((item, index) => {
              this.currentNodeForm = this.formDataList[index];
              this.currentNodeIndex = index;
              item.validate(valid => {
                if (!valid) {
                  checkFlag = false;
                }
              });
            });
            if(checkFlag){
              //保存更新
              let nodeName = null;
              //组装优化param
              let params = this.formDataList.map((ele, index) => {
                let itemParam = JSON.parse(JSON.stringify(ele));
                if(ele.eventRangeTime){
                  itemParam.eventRangeTime = {
                    f: ele.eventRangeTime[0],
                    s: ele.eventRangeTime[1],
                  };

                  if(this_.tripInfo.timeType == 1) {
                    var tripStartTime  = new Date(this_.tripInfo.startTime).getTime();
                    var tripEndTime  = new Date(this_.tripInfo.endTime).getTime();
                    if(!(tripStartTime <=  ele.eventRangeTime[0] && ele.eventRangeTime[1] <= tripEndTime)){
                      return this_.$message({
                        type: 'error',
                        message: '时间条件必须在旅程时间范围内'
                      })
                    }
                  }

                }
                Object.keys(itemParam).forEach((ele, index) => {
                  if(!checkRemoveJsonProperties(this.ruleForm.eventCode, ele)){
                    delete itemParam[ele];
                  }
                });
                // 取第一个表单的名称
                if(!nodeName){
                  nodeName = ele.eventName;
                }
                return itemParam;
              });

              let callback = function(res) {
                if (res.code == "0000") {
                  this_.$emit("saveLabelData",{nodeName:nodeName});
                  this_.handleClose();
                }
              };

              this.ruleForm.nodeVariable = JSON.stringify(params);
              this.ruleForm.id = this.nodeInfo.nodeId;
              this.utils.request.updateBranchNode(this.ruleForm, callback);
            }
          }
        });
      },

      //获取优惠券红包列表
      getCouponsList(query) {
        let this_ = this;
        if (query !== '') {
          let callback = function(res) {
            if (res.code == "0000") {
              this_.activeStatus = res.data.rows;
            } else {
              //alert("修改失败");
            }
          };
          this.loadPromsing = true;
          setTimeout(() => {
            this.loadPromsing = false;
            let promType = this.ruleForm.eventCode == 'coupons_verification' ?  11 : 12;
            let param = {
              promType: promType,
              promName: query,
              limit: 1000000,
              start: 1,
            };
            this.utils.request.getCouponList(param, callback);
          }, 10);
        } else {
          this_.getCouponList();
        }
      },

      getDefalutItemFrom(){
        return [
          {
            eventName: null,                    // 事件条件
            eventRangeTime: [],                         // 时间条件
            memberNum: null,                 // 会员事件-级别数
            promCode: null,         // 优惠券红包核销事件-优惠券红包活动code
            verificationChannels: null,         // 优惠券红包核销事件-优惠券红包活动核销渠道
            pointsExchangeContent: null,         // 积分兑换内容
            pointsExchangeNum: null,          // 积分兑换次数

            pointsCashInAmount:{
              s: null,
              f: null
            },
            pointsCashInNum: null,
          }
        ];
      },

      //获取节点详情
      getBranchNodeDetail(){
        let this_ = this;
        let callback = function(res) {
          if (res.code == "0000") {
            this_.ruleForm.eventType = res.data.eventType == 0 ? null : res.data.eventType;
            this_.eventCodeList = getEventCodeListByType(this_.ruleForm.eventType);
            this_.ruleForm.eventCode =  res.data.eventCode == 0 ? null : res.data.eventCode;
            let nodeVariable = JSON.parse(res.data.nodeVariable);
            if(this_.ruleForm.eventCode){
              let callbackCoupon = function(res) {
                if (res.code == "0000") {
                  this_.activeStatus = res.data.rows;
                  if(nodeVariable){
                    this_.formDataList = nodeVariable.map((ele, index) => {
                      let itemForm = JSON.parse(JSON.stringify(ele));
                      itemForm.eventRangeTime = [];
                      if(ele.eventRangeTime){
                        itemForm.eventRangeTime[0] = ele.eventRangeTime.f;
                        itemForm.eventRangeTime[1] = ele.eventRangeTime.s;
                      }
                      //判断promCode是否在列表中
                      let coupon = this_.activeStatus.find(function (item, index) {
                        return item.promotionId == itemForm.promCode;
                      });
                      if(typeof(coupon)=="undefined"){
                        itemForm.promCode = null;
                      }
                      return itemForm;
                    });
                  }

                } else {
                  //alert("修改失败");
                }
              };
              let promType = this_.ruleForm.eventCode == 'coupons_verification' ?  11 : 12;
              let param = {
                promType: promType,
                limit: 1000000,
                start: 1,
              };
              this_.utils.request.getCouponList(param, callbackCoupon);
            }
          }
        };
        let param = {"branchNodeId": this.nodeInfo.nodeId};
        this.utils.request.getBranchNodeDetail(param, callback);
      },

      //子关闭 标签选择弹框
      handleClose() {
        this.$emit("handleClose", false);
      },

      //获取旅程详情
      getTripDetailAndNodeList(){
        let this_ = this;
        let callback = function(res) {
          if (res.code == "0000") {
              this_.tripInfo = res.data;
              //固定时间
              if(res.data.timeType == 1){
                this_.tripEnd = res.data.endTime;
                this_.tripStart = res.data.startTime;
              }
          }
        };
        let param = {"tripId": this.journeyId};
        this.utils.request.getTripDetailAndNodeList(param, callback);
      },

      //获取优惠券红包列表
      getCouponList(){
        let this_ = this;
        let callback = function(res) {
          if (res.code == "0000") {
            this_.activeStatus = res.data.rows;
          } else {
            //alert("修改失败");
          }
        };
        if(this.ruleForm.eventCode){
          let promType = this.ruleForm.eventCode == 'coupons_verification' ?  11 : 12;
          let param = {
            promType: promType,
            limit: 1000000,
            start: 1,
          };
          this.utils.request.getCouponList(param, callback);
        }
      },

    },

    mounted() {
      this.getBranchNodeDetail();
      this.getTripDetailAndNodeList();
    },
  }
</script>
<style lang="scss" scoped>
  .desc{
    color: #C4C4C4;
    font-size: 12px;
  }

  // /deep/ .el-form-item__error{
  //   width: 500px;
  // }

  // .inLine{
  //   margin-top: 5px;
  // }

  // .redColor{
  //   color:#F00
  // }

  // .wrap {
  //   padding: 0 30px;
  //   text-align:center;
  //   /* 表单样式 */
  //   .form-wrap {
  //     overflow: hidden;
  //     width: 100%;
  //     padding: 20px 0;
  //     .lebel {
  //       float: left;
  //       text-align: right;
  //       color: #999999;
  //       font-size: 16px;
  //     }
  //     .form {
  //       float: left;
  //       border: 1px solid #DCDFE6 !important;
  //       padding: 20px;
  //       margin-left: 10px;
  //       border: 1px solid;
  //       width: 80%;
  //     }
  //     .commonForm {
  //       position: relative;
  //       .delete {
  //         position: absolute;
  //         right: 0;
  //         top: 0;
  //         font-size: 22px;
  //         cursor: pointer;
  //         z-index: 999;
  //       }
  //     }
  //     .addForm {
  //       color: green;
  //     }
  //   }
  // }
  .noMargin{
  /deep/ .el-form-item__content{
    margin-right: 0 !important;
  }
}
.noMarginBottom{
  margin-bottom: 0 !important;  
}
/deep/ .w225{
  width: 225px !important;
  .el-input__inner{
    width: 225px !important;
  }
}
.label{
  float: left;
}
.mt30{
  margin-top: 30px !important;
}
.form{
  border: 1px solid #999999;
  margin-left: 90px;
  padding: 30px;
  border-radius: 4px;
  width: 480px;
  /deep/ .el-form-item{
    margin-right: 0 !important;
     .el-form-item__content{
    margin-right: 0 !important;
  }
  }
  
}
.labelColor666{
  /deep/ .el-form-item__label{
    color: #666666;
  }
}
.labelSize14{
  /deep/ .el-form-item__label{
    font-size: 14px !important;
  }
}
/deep/ .w244{
  width: 244px !important;
  .el-input__inner{
    width: 244px !important;
  } 
}
.labelMarginLeft8{
  /deep/ .el-form-item__label{
    margin-left: 8px;
  }
}
.labelMarginLeft14{
  /deep/ .el-form-item__label{
    margin-left: 14px;
  }
}
.labelMarginLeft5{
  /deep/ .el-form-item__label{
    margin-left: 5px;
  }
}
.labelMarginLeft28{
  /deep/ .el-form-item__label{
    margin-left: 28px;
  }
}
.labelMarginLeft20{
  /deep/ .el-form-item__label{
    margin-left: 20px;
  }
}
/deep/ .w390{
width: 390px !important;
.el-input__inner{
  width: 390px !important;
}
}
.noMarginBottom{
 margin-bottom: 0 !important;
}
.mb10{
  margin-bottom: 10px !important;
}
.addBtn{
  font-size: 12px !important;
}
/deep/ .w385{
  width: 385px !important;
  .el-input__inner{
    width: 385px !important;
  }
}
/deep/ .w360{
  width: 360px !important;
  .el-input__inner{
    width: 360px !important;
  }
}
/deep/ .w215{
  width: 215px !important;
  .el-input__inner{
    width: 215px !important;
  }
}
/deep/ .iw100{
  width: 155px !important;
  .el-input__inner{
    width: 155px !important;
  }
}
.labelMarginLeft25{
  /deep/ .el-form-item__label{
    margin-left: 25px !important;
  }
}
.labelMarginLeft16{
  /deep/ .el-form-item__label{
    margin-left: 16px !important;
  }
}
</style>

